package com.my.socket.nio.v13;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * Created by ZhongGang
 * at 2018/7/4 11:13
 */
public class Processor {
    private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class);

    public void process(SelectionKey selectionKey) {
        try {
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            socketChannel.configureBlocking(false);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = socketChannel.read(byteBuffer);
            byteBuffer.flip();
            String message = new String(byteBuffer.array());
            LOGGER.info("read: {}", message);

            byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put(message.getBytes());
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            socketChannel.close();
            LOGGER.info("write: {}", message);
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", e.getMessage());
        }
    }
}
